package com.example;

import com.example.net.ImgUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.pdfbox.util.PDFMergerUtility;

import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class ConvertPdfUtil {

    /**
     * @description: 图片转pdf，以字节数组的形式返回
     * @author: zhuangxl
     * @since: 2021/7/12 17:14
     * @param bufferedImage: 图片
     * @param type: 图片扩展类型
     * @return: byte[]
     **/
    public static byte[] img2pdf(BufferedImage bufferedImage, String type) throws Exception{

        log.info("转为pdf中...");

        // 返回对象
        byte[] originalBytes = null;

        // 目标文件地址
        String fileName = "/"+System.currentTimeMillis()+".pdf";
        String filePath = FileUtils.getTempDirectoryPath() + File.separator + fileName;

        try {

            Document document = new Document(null, 30, 30, 30, 30);

             //图片流处理
            document.setPageSize(new Rectangle(bufferedImage.getWidth() + 60, bufferedImage.getHeight() + 60));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, type, out);
            byte[] b = out.toByteArray();
            Image image = Image.getInstance(b);

            // 图片转为pdf
            log.info("临时文件地址：{}", filePath);
            FileOutputStream fos = new FileOutputStream(filePath);
            PdfWriter.getInstance(document, fos);
            document.open();
            document.add(image);
            document.close();
            fos.close();

            originalBytes = getFileBytes(filePath);

        } finally {
            File file = new File(filePath);
            boolean flag = file.delete();
            log.info("临时文件删除：{}" , flag);
        }

        return originalBytes;
    }

    /**
     * @description: pdf合并
     * @author: zhuangxl
     * @since: 2021/7/12 17:27
     * @param byteArrayList: pdf文件列表
     * @return: void
     **/
    public static byte[] mergePDF(List<byte[]> byteArrayList) throws Exception{

        log.info("pdf合并中...");

        // 返回对象
        byte[] originalBytes = null;

        // 临时文件地址列表
        List<String> fileTempList = new ArrayList<>();

        // pdf合成工具
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        try {

            int i = 0;
            for (byte[] bytes:byteArrayList) {

                String fileNameTemp = "/"+System.currentTimeMillis() + i + ".pdf";
                String filePathTemp = FileUtils.getTempDirectoryPath() + File.separator + fileNameTemp;
                log.info("临时文件地址：{}", filePathTemp);

                FileUtils.writeByteArrayToFile(new File(filePathTemp), bytes, 0, bytes.length);

                mergePdf.addSource(filePathTemp);

                fileTempList.add(filePathTemp);

                i++;
            }

            // 目标文件地址
            String fileName = "/"+System.currentTimeMillis() + ".pdf";
            String filePath = FileUtils.getTempDirectoryPath() + File.separator + fileName;
            fileTempList.add(filePath);
            log.info("临时文件地址：{}", filePath);

            // 目标文件合成
            mergePdf.setDestinationFileName(filePath);
            mergePdf.mergeDocuments();
            log.info("pdf合并完成");

            originalBytes = getFileBytes(filePath);

        } finally {

            for(String filePath:fileTempList){
                File file = new File(filePath);
                boolean flag = file.delete();
                log.info("临时文件删除：{}" , flag);
            }

        }

        return originalBytes;

    }

    /**
     * @description: 以字节数组的形式读取文件
     * @author: zhuangxl
     * @since: 2021/7/12 17:55
     * @param filePath: 文件地址
     * @return: byte[]
     **/
    public static byte[] getFileBytes(String filePath) throws IOException {

        byte[] originalBytes = null;

        FileInputStream inputStream = new FileInputStream(filePath);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = bufferedInputStream.read(buffer, 0, 8192)) != -1) {
            originalBytes = ArrayUtils.addAll(originalBytes, Arrays.copyOf(buffer, bytesRead));
        }

        bufferedInputStream.close();
        inputStream.close();

        return originalBytes;
    }
}